import { showToast } from '@/utils/toast.js';

// 配置后端接口基础URL
const baseUrl = 'https://www.bugbustersclub.cn/longchuan';
// const baseUrl = 'https://dc8y0g.top/longchuan';
// const baseUrl = 'http://localhost:8094/longchuan';

// 请求拦截器
const requestInterceptor = (config) => {
  // 获取token
  const token = uni.getStorageSync('token');

  // 如果有token则添加到请求头
  if (token) {
    config.header = {
      ...config.header,
      token,
    };
  }

  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  // 这里可以对响应数据做处理
  const { data } = response;

  // 如果返回401，表示登录过期或未登录
  if (data.code === 401) {
    // 清除token和用户信息
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');

    // 显示提示
    showToast(data.msg || '登录已过期，请重新登录');

    // 跳转到登录页
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login',
      });
    }, 1500);

    return Promise.reject(response);
  }

  return response;
};

// 请求错误处理
const requestErrorHandler = (error) => {
  showToast('请求发送失败，请检查网络连接');
  return Promise.reject(error);
};

// 响应错误处理
const responseErrorHandler = (error) => {
  showToast('请求失败，服务器异常');
  return Promise.reject(error);
};

// HTTP请求工具
const http = {
  baseUrl,

  // GET请求
  get(url, params = {}) {
    return new Promise((resolve, reject) => {
      // 构建查询字符串
      let queryString = '';
      if (Object.keys(params).length > 0) {
        queryString = `?${Object.keys(params)
          .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&')}`;
      }

      // 发起请求
      uni.request({
        url: baseUrl + url + queryString,
        method: 'GET',
        ...requestInterceptor({}),
        success: (res) => {
          try {
            resolve(responseInterceptor(res));
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(requestErrorHandler(error));
        },
      });
    });
  },

  // POST请求
  post(url, data = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: baseUrl + url,
        method: 'POST',
        data,
        ...requestInterceptor({}),
        success: (res) => {
          try {
            resolve(responseInterceptor(res));
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(requestErrorHandler(error));
        },
      });
    });
  },

  // PUT请求
  put(url, data = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: baseUrl + url,
        method: 'PUT',
        data,
        ...requestInterceptor({}),
        success: (res) => {
          try {
            resolve(responseInterceptor(res));
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(requestErrorHandler(error));
        },
      });
    });
  },

  // DELETE请求
  delete(url, data = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: baseUrl + url,
        method: 'DELETE',
        data,
        ...requestInterceptor({}),
        success: (res) => {
          try {
            resolve(responseInterceptor(res));
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(requestErrorHandler(error));
        },
      });
    });
  },
};

export default http;
